package com.pn.filter;

import com.alibaba.fastjson.JSON;
import com.pn.entity.Result;
import com.pn.utils.WarehouseConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

public class LoginCheckFilter implements Filter {

    private StringRedisTemplate stringRedisTemplate;

    public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate){
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1、白名单直接放行
        List list = new ArrayList();
        list.add("/captcha/captchaImage");
        list.add("/login");
        list.add("/product/img-upload");
        list.add("/doc.html");
        list.add("/doc.html/**");
        list.add("/swagger-ui.html");
        list.add("/swagger-resources");
        list.add("/v2/api-docs");
        list.add("/swagger-ui/**");
        //获取当前路径
        String path = request.getServletPath();
        if (list.contains(path) || path.contains("/img/upload")){
            filterChain.doFilter(request,response);
            return;
        }
        //2、其他请求查看是否有token，redis是否存在数据
        String header = request.getHeader(WarehouseConstants.HEADER_TOKEN_NAME);
        if (StringUtils.hasText(header) && stringRedisTemplate.hasKey(header)){
            filterChain.doFilter(request,response);
            return;
        }
        Result result = Result.err(406,"您未登录");
        String jsonString = JSON.toJSONString(result);
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.println(jsonString);
        writer.flush();
        writer.close();
    }
}
